window.onload = function () {
    if (window.history && window.history.pushState) {
        window.history.pushState(null, null, document.URL);
        window.addEventListener('popstate', function () {
            window.history.pushState(null, null, document.URL);
        });
    }
};

function registerUser() {
    const username = document.getElementById('register-username').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const emailInput = document.getElementById('register-email');

    if (!username || !email || !password || !confirmPassword) {
        alert('不可为空');
        return;
    }
    /*邮箱验证*/
    if (!emailInput.checkValidity()) {
        emailInput.classList.add('is-invalid');
        return;
    }
    emailInput.classList.remove('is-invalid');/*邮箱格式正确移除已存在is-invalid的类名*/

    // 检查密码和确认密码是否匹配
    if (password !== confirmPassword) {
        alert('密码和确认密码不匹配');
        return;
    }

    const userData = {
        username: username,
        email: email,
        password: password
    };

    axios.post('http://localhost:8080/register', userData, {
        headers: {
            'Content-Type': 'application/json'
        },
        withCredentials: true
    })
        .then(response => {
            console.log(response.data);
            if (response.status === 200) {
                alert('注册成功');
                // 关闭模态框
                $('#registerModal').modal('hide');
                location.reload(); // 刷新页面以反映更改
            } else if (response.status === 409) {
                alert('用户名已存在');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (error.response && error.response.data) {
                alert(error.response.data); // 显示后台返回的具体错误信息
            } else {
                alert('注册失败');
            }
        });
}